package controllers;

import models.Employe;
import models.requete;

import java.lang.Integer;import java.lang.String;
import org.apache.commons.mail.*;

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * Created by richard on 13/06/14.
 */
public class MonMail {
 /*   String smtpHost = Play.application().configuration().getString("smtp.host");
    Integer smtpPort = Play.application().configuration().getInt( "smtp.port" );
    String smtpUser = Play.application().configuration().getString( "smtp.user" );
    String smtpPassword = Play.application().configuration().getString( "smtp.password"
*/

    
    
    /*String smtpHost = "";
    static Integer smtpPort=25;
    static String smtpUser="";
    static String smtpPassword="" ;
    static String AdresseMailFrom= "richard.urunuela@irccyn.ec-nantes.fr";
    static String HostName= "smtp.irccyn.ec-nantes.fr";
    static boolean SSL=false;
*/

   /* static Integer smtpPort=587;
    static String smtpUser="richard.urunuela@icloud.com";
    static String smtpPassword="secret1602" ;
    static String AdresseMailFrom= "richard.urunuela@icloud.com";
    static String HostName= "smtp.mail.me.com";
    static boolean SSL=true;
*/
    static Integer smtpPort=587;
    static String smtpUser="ierdremail@gmail.com";
    static String smtpPassword="12se34cre56t" ;
    static String AdresseMailFrom= "ierdremail@gmail.com";
    static String HostName= "smtp.gmail.com";
    static boolean SSL=false;
    
    public static void sendEmptyMail(){
        Email email = new SimpleEmail();
        try {
            email.setFrom (AdresseMailFrom);

            email.addTo("ierdremail@gmail.com");

            email.setHostName(HostName);
            email.setSmtpPort(smtpPort);
            email.setSSLOnConnect( SSL);
           


           email.setSubject("subject TEST");
        email.setMsg("Message");
        email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }


    }

    public static void receiveMail(){
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3s");
        props.put("mail.pop3s.auth", "true");

        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            MonLogger.log("[SCAN MAIL] ");
            store.connect("pop.gmail.com",995,"ierdremail@gmail.com", "12se34cre56t");

            Folder inbox = store.getFolder("INBOX");

            inbox.open(Folder.READ_WRITE);
            if (inbox.getMessageCount() == 0) {
                 System.out.println("message O OO " );
             return;   
            }
            Message msg = inbox.getMessage(inbox.getMessageCount());

            System.out.println("message " + inbox.getMessageCount());
            Address[] in = msg.getFrom();



            Message[] messages = inbox.getMessages();
            for (int i = 0; i < messages.length; i++) {
                msg = messages[i];
                MonLogger.log("[RECEPTION] " + msg.getMessageNumber());
                in = msg.getFrom();

                String adresseMail ="";
                for (Address address : in) {
                    adresseMail=address.toString();
                }
                if (adresseMail.contains("<")) {
                    int deb = adresseMail.indexOf("<")+1;
                    int fin = adresseMail.indexOf(">");
                    adresseMail = adresseMail.substring(deb,fin);
                }
                //System.out.println("SUBJECT:" + msg.getSubject());
                //System.out.println("CONTENT:" + msg.getContent());



                 //System.out.println(Employe.find.all());

                Employe emp= Employe.find.where().eq("adresseMail",adresseMail).findUnique();

                if (emp==null) {
                    //System.out.println("NOT OK");
                    MonLogger.log("[MSG RECU MAIS ADD INVALIDE] " + adresseMail);

                }
                else {
                    //System.out.println("OK");
                    MonLogger.log("[MSG RECU OK] " + emp.toLog());

                    //Parse commande et on extrait la requete
                    requete req = new requete();
                    req.from = emp;
                   // req.commande =  msg.getContent()+"";

                    Object msgContent = msg.getContent();
                    
                    //MESSAGE CONTENT
                    String content = "";
                    
                    /* Check if content is pure text/html or in parts */
                    if (msgContent instanceof Multipart) {
                        
                        Multipart multipart = (Multipart) msgContent;
                        
                       // Log.e("BodyPart", "MultiPartCount: "+multipart.getCount());
                        content = multipart.getBodyPart(0).getContent().toString();
                      /*  for (int j = 0; j < multipart.getCount(); j++) {
                            System.out.println("--"+ j + " -- "+multipart.getBodyPart(j).getContent().toString());
                            BodyPart bodyPart = multipart.getBodyPart(j);
                            
                            String disposition = bodyPart.getDisposition();
                            
                            if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) {
                                System.out.println("Mail have some attachment");
                                
                                DataHandler handler = bodyPart.getDataHandler();
                                System.out.println("file name : " + handler.getName());                                 
                            }
                            else { 
                                //content = getText(bodyPart);  // the changed code

                               // System.out.println(bodyPart.getContent().toString());



                                content = "";
                            }
                        }*/
                    }
                    else {
                        content = msg.getContent() + "";
                    }

                      req.commande =  content+"";
                    
                    //****
                    
                    req.date = new Date();
                    req.initCmde();
                    req.startCmde();
                    //System.out.println(req );


                }




        //DELETE MESSSAGE
                msg.setFlag(Flags.Flag.DELETED,true);


            }
            //DELETE MESSSAGE
            inbox.close(true);



           /* Multipart mp = (Multipart) msg.getContent();
            BodyPart bp = mp.getBodyPart(0);
            System.out.println("SENT DATE:" + msg.getSentDate());
            System.out.println("SUBJECT:" + msg.getSubject());
            System.out.println("CONTENT:" + bp.getContent());*/
        } catch (Exception mex) {
            mex.printStackTrace();
        }

    }


    public static void sendMailText(String adressseMail,String sujet,  String msg) {
        Email email = new SimpleEmail();
        try {
            email.setFrom (AdresseMailFrom);

            email.addTo(adressseMail);

            email.setHostName(HostName);
            email.setSmtpPort(smtpPort);
            email.setSSLOnConnect( SSL);
            
            email.setHostName("smtp.gmail.com");
            
            
            email.setAuthenticator(new DefaultAuthenticator("ierdremail@gmail.com","12se34cre56t"));

            email.getMailSession().getProperties().put("mail.smtps.auth", "true");
            email.getMailSession().getProperties().put("mail.debug", "true");
            email.getMailSession().getProperties().put("mail.smtps.port", "587");
            email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587");
            email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",   "javax.net.ssl.SSLSocketFactory");
            email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");

            email.setSubject(sujet);
            email.setMsg(msg);
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

    }
    public static void sendMailTextWithFile(String adressseMail,String sujet,  String msg,String file) {

        EmailAttachment attachement = new EmailAttachment();
        MultiPartEmail email = new MultiPartEmail();
        try {

            // Fichier
            attachement.setPath(file);
            attachement.setDisposition(EmailAttachment.ATTACHMENT);
            attachement.setDescription("planning");
            attachement.setName("planning.pdf");
            //fichier

            email.setFrom (AdresseMailFrom);

            email.addTo(adressseMail);

            email.setHostName(HostName);
            email.setSmtpPort(smtpPort);
            email.setSSLOnConnect( SSL);

            email.setHostName("smtp.gmail.com");


            email.setAuthenticator(new DefaultAuthenticator("ierdremail@gmail.com","12se34cre56t"));

            email.getMailSession().getProperties().put("mail.smtps.auth", "true");
            email.getMailSession().getProperties().put("mail.debug", "true");
            email.getMailSession().getProperties().put("mail.smtps.port", "587");
            email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587");
            email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",   "javax.net.ssl.SSLSocketFactory");
            email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");

            email.setSubject(sujet);
            email.setMsg(msg);

            email.attach(attachement);
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }
}
